import React, { Component } from 'react';
import {
  StyleSheet, View, ScrollView, Text, Button,
} from 'react-native';

const APP_ID = 'hqimjzoqrmzfloih';
const APP_SECRET = 'TFdPYmRiN1VoSU1TQUc3RElLOFgxZz09';
// appid 一天就会过期

// 开放API：https://github.com/MZCretin/RollToolsApi
// 没有跨域的限制
class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      response: '',
    };
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  fetchGet() {
    console.log('fetchGet');
    const that = this;
    fetch(`http://www.mxnzp.com/api/holiday/single/20181121?app_id=${APP_ID}&app_secret=${APP_SECRET}`, {
      method: 'GET',
    }).then((response) => response.json())
      .then((res) => {
        console.log('fetchGet res:', res);
        that.setState({ response: JSON.stringify(res, null, 4) });
      }).catch((error) => {
        console.log('fetchGet error:', error);
      });
  }

  async fetchGetAsyncAwait() {
    console.log('fetchGetAsyncAwait');
    const that = this;
    try {
      const response = await fetch(`http://www.mxnzp.com/api/holiday/single/20181121?app_id=${APP_ID}&app_secret=${APP_SECRET}`);
      const res = await response.json();
      console.log('fetchGetAsyncAwait res:', res);
      that.setState({ response: JSON.stringify(res, null, 4) });
    } catch (error) {
      console.log('fetchGetAsyncAwait error:', error);
    }
  }

  fetchPost() {
    console.log('fetchPost');
    const that = this;
    const data = {
      app_id: APP_ID,
      app_secret: APP_SECRET,
      content: '你好',
      size: 600,
      logo_size: 500,
      type: 0,
      logo_img: '',
    };
    fetch('http://www.mxnzp.com/api/qrcode/create/logo/', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json', // 提交数据的格式关键取决于 Content-Type
      },
      body: JSON.stringify(data),
    }).then((response) => response.json())
      .then((res) => {
        console.log('fetchPost res:', res);
        that.setState({ response: JSON.stringify(res, null, 4) });
      }).catch((error) => {
        console.log('fetchPost error:', error);
      });
  }

  render() {
    return (
      <View style={styles.contain}>
        <View style={styles.btnView}>
          <Button
            onPress={this.fetchGet.bind(this)}
            title="fetchGet"
          />
          <Button
            onPress={this.fetchGetAsyncAwait.bind(this)}
            title="fetchGetAsyncAwait"
          />
          <Button
            onPress={this.fetchPost.bind(this)}
            title="fetchPost"
          />
        </View>
        <ScrollView style={styles.response}>
          <Text>{this.state.response}</Text>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  contain: {
    flex: 1,
  },
  btnView: {
    flexDirection: 'row',
  },
  response: {
    height: 50,
    backgroundColor: 'yellow',
  },
});
export default MyComponent;
